package com.shujia.window

import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.{SlidingProcessingTimeWindows, TumblingProcessingTimeWindows}
import org.apache.flink.streaming.api.windowing.time.Time

object Demo1TImeWindow {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
      * 统计最近15秒单词的数量每隔5秒统计一次
      *
      */

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val kvDS: DataStream[(String, Int)] = linesDS.flatMap(_.split(",")).map((_, 1))

    val keyByDS: KeyedStream[(String, Int), String] = kvDS.keyBy(_._1)

    /**
      * 时间窗口
      * SlidingProcessingTimeWindows： 滑动的处理时间窗口， 需要设置窗口大小和滑动时间
      * TumblingProcessingTimeWindows： 滚动的处理时间窗口,窗口没有交叉
      * SlidingEventTimeWindows: 滑动的事件时间窗口， 数据中必须有时间端
      * TumblingEventTimeWindows： 滚动的事件事件窗口
      */

    val countDS: DataStream[(String, Int)] = keyByDS
      //滑动窗口
      .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
      .sum(1)

    countDS.print()

    env.execute()
  }

}
